package creational.property.copy.deep;

import java.io.*;

/**
 * 这是一个猴子类，他实现了 Cloneable 用于提供复制方法
 * 实现了 Serializable 类，让他能够支持深拷贝
 */
public class MonkeyCS implements Cloneable, Serializable {

    private String name;
    private String age;
    private ClubS club;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public ClubS getClub() {
        return club;
    }

    public void setClub(ClubS club) {
        this.club = club;
    }

    @Override
    protected Object clone() {
        Object objResult = null;

        try {
            objResult = super.clone();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return objResult;
    }

    /**
     * 通过序列化进行深度拷贝
     * @return
     */
    public Object deepClone() {
        Object objResult = null;

        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(this);

            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            objResult = objectInputStream.readObject();

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return objResult;
    }

    @Override
    public String toString() {
        return "MonkeyC{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", club=" + club +
                '}';
    }
}
